package com.tancire.file.service.impl;

import com.tancire.common.utils.StringUtils;
import com.tancire.file.bean.SaveFileBean;
import com.tancire.file.config.MinioConfig;
import com.tancire.file.service.ISysFileService;
import com.tancire.file.utils.FileUploadUtils;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Minio 文件存储
 *
 * @author healthy
 */

@Service
public class MinioSysFileServiceImpl implements ISysFileService {

    @Resource
    private MinioConfig minioConfig;

    @Resource
    private MinioClient client;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public SaveFileBean uploadFile(MultipartFile file, String auth) throws Exception {
        String fileName = FileUploadUtils.extractFilename(file);
        String bucketName = minioConfig.getBucketName();
        if ("Y".equals(auth)) {
            bucketName = minioConfig.getPrvBucketName();
        }
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        return new SaveFileBean(minioConfig.getBucketName(), fileName, minioConfig.getUrl(), minioConfig.getAccessUrl(), file.getSize(), auth);
    }

    /**
     * 图片预览
     *
     * @param res
     * @param path
     */
    @Override
    public void previewFile(HttpServletResponse res, String path) throws Exception {
        // 获取文件流
        InputStream is = client.getObject(GetObjectArgs.builder().bucket(minioConfig.getPrvBucketName()).object(path).build());
        OutputStream os = res.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        try {
            while ((len = is.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                // 不处理
            }
        }
    }

    private String getContentType(String path) {
        if (StringUtils.isNotBlank(path)) {
            String[] split = path.split(".");
            String suffix = split[split.length - 1];
            if (StringUtils.isNotBlank(suffix)) {
                if ("png".equalsIgnoreCase(suffix) || "jpg".equalsIgnoreCase(suffix)
                        || "jpeg".equalsIgnoreCase(suffix) || "gif".equalsIgnoreCase(suffix)) {
                    return "image/" + suffix.toLowerCase();
                } else if ("mp4".equalsIgnoreCase(suffix)) {
                    return "video/" + suffix.toLowerCase();
                }
            }
        }
        return null;
    }
}
